const mongoose = require('mongoose')
const { ObjectId } = mongoose.Types
const { Order } = require('../../schema')

mongoose.connect('mongodb://127.0.0.1:27017/sportswear').then()
const orderCollection = mongoose.model('order', Order)

const reference = [{
    $lookup: {
        from: 'shops',
        localField: 'proid',
        foreignField: 'proid',
        as: 'product'
    }
}, {
    $lookup: {
        from: 'addresses',
        localField: 'addressid',
        foreignField: 'addressid',
        as: 'address'
    }
}]

function insertOrder (userid, addressid, proid, count, size) {
    const orderid = ObjectId()
    return new Promise(resolve => {
        const record = new orderCollection({
            orderid,
            userid,
            addressid,
            proid,
            state: 0,
            count: count || 1,
            size: size || 'xl',
            time: new Date(new Date().getTime() + 8 * 60 * 60 * 1000),
            comment: false
        })
        record.save().then(res => {
            resolve(orderid)
        }).catch(err => {
            resolve('添加失败')
        })
    })
}

function getOrderList (userid) {
    return new Promise(resolve => {
        try {
            orderCollection.aggregate([
                ...reference,
                {
                    $match: {
                        userid: ObjectId(userid)
                    }
                }
            ]).sort({ operation: -1 }).then(res => {
                resolve(format(res))
            }).catch(err => {
                resolve('获取订单信息失败')
            })
        } catch (e) {
            resolve('id不合法')
        }
    })
}

function getAllOrderList (state = 0) {
    const sort = {}
    if (state === 0) {
        sort.time = -1
    } else {
        sort.operation = -1
    }
    return new Promise(resolve => {
        try {
            orderCollection.aggregate([
                ...reference,
                {
                    $match: {
                        state
                    }
                }
            ]).sort(sort).then(res => {
                resolve(format(res))
            }).catch(err => {
                resolve('获取订单信息失败')
            })
        } catch (e) {
            resolve('id不合法')
        }
    })
}

function getOrderByState (userid, state) {
    const sort = {}
    if (state === 0) {
        sort.time = -1
    } else {
        sort.operation = -1
    }
    return new Promise(resolve => {
        try {
            orderCollection.aggregate([
                ...reference,
                {
                    $match: {
                        userid: ObjectId(userid),
                        state,
                    }
                }
            ]).sort(sort).then(res => {
                resolve(format(res))
            }).catch(err => {
                resolve('获取订单信息失败')
            })
        } catch (e) {
            resolve('id不合法')
        }
    })
}

function getOrderDetail (orderid) {
    return new Promise(resolve => {
        try {
            orderCollection.aggregate([
                ...reference,
                {
                    $match: {
                        orderid: ObjectId(orderid)
                    }
                }, {
                    $project: {
                        _id: false,
                    }
                }
            ]).then(res => {
                resolve(res[0])
            }).catch(err => {
                resolve('获取订单详情失败')
            })
        } catch (err) {
            resolve('id不合法')
        }
    })
}

function modifyOrderState (orderid, state, msg = '') {
    return new Promise(resolve => {
        try {
            orderCollection.updateOne({
                orderid
            }, {
                state,
                msg,
                operation: new Date(new Date().getTime() + 8 * 60 * 60 * 1000)
            }).then(res => {
                if (res.modifiedCount) {
                    resolve('订单状态修改成功')
                } else {
                    resolve('状态保持不变')
                }
            }).catch(err => {
                resolve('订单状态修改失败')
            })
        } catch (e) {
            resolve('id不合法')
        }
    })
}

function format (data) {
    return data.map(item => {
        return {
            orderid: item.orderid,
            proid: item.proid,
            userid: item.userid,
            addressid: item.addressid,
            msg: item.msg,
            state: item.state,
            count: item.count,
            size: item.size,
            time: item.time,
            operation: item.operation,
            comment: item.comment,
            proname: item.product[0] && item.product[0].proname || '商品已删除',
            originprice: item.product[0] && item.product[0].originprice || 0,
            discount: item.product[0] && item.product[0].discount || 0,
            img1: item.product[0] && item.product[0].swiper[0],
            name: item.address[0] && item.address[0].name || '地址已删除',
            tel: item.address[0] && item.address[0].tel || '地址已经删除',
            province: item.address[0] && item.address[0].province || '地址已删除',
            city: item.address[0] && item.address[0].city || '地址已删除',
            county: item.address[0] && item.address[0].county || '地址已删除',
            addressDetail: item.address[0] && item.address[0].addressDetail || '详细地址删除',
        }
    })
}

module.exports = {
    insertOrder,
    getOrderDetail,
    getOrderList,
    getAllOrderList,
    getOrderByState,
    modifyOrderState
}
